16. Calculated Properties

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

Calculated Properties in PowerShell are custom derived (Calculated) properties. It lets the user to format a certain property in a way he want it to be. The calculation(expression) can be a quite possibly anything.

PowerShell understands the abbreviations KB, MB, GB, TB, and PB as representing the base-2 values kilobyte, megabyte, gigabyte, terabyte, and petabyte, respectively.

16.1: Display file size in KB - Calculated Properties

Let's consider the below snippet,

1
Get-ChildItem -Path C:\MyFolder | Select-Object Name, CreationTime, Length

It simply output the folder content with the selected properties. Something like,

What if I want to display the file size in KB? This is where calcualted properties comes handy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Get-ChildItem C:\MyFolder | Select-Object Name, @{Name="Size_In_KB";Expression={$_.Length / 1Kb}}


## 16.2: Display a list of processes that includes each process’ name, ID, virtual memory use and paged memory use

This new example changes the column labels to include the MB designation. It also changes the expressions to include a division
operation, dividing each memory value by 1 MB.

```Powershell
Get-Process |
Select-Object -Property Name,
ID,
@{
  n = 'VirtualMemory(MB)'
  e = {
    $PSItem.VM / 1MB
  }
},
@{
  n = 'PagedMemory(MB)'
  e = {
    $PSItem.PM / 1MB
  }
}

Unfortunately, the resulting values have several decimal places, which is unattractive. Consider this revision:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Get-Process |
Select-Object -Property Name,
ID,
@{
  n = 'VirtualMemory(MB)'
  e = {
    '{0:N2}' -f ($PSItem.VM / 1MB)
  }
},
@{
  n = 'PagedMemory(MB)'
  e = {
    '{0:N2}' -f ($PSItem.PM / 1MB)
  }
}

This new example uses Windows PowerShell’s –f formatting operator. To the left of the operator is a string that tells Windows PowerShell what data to display. {0:N2} means to display the first data item as a number with two decimal places. To the right of the operator is the original mathematical expression. It is in parentheses to make sure that it executes as a single unit.